import os
import sys
import datetime
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class Calendar(QWidget):

    # 自定义信号,需要在类最高级别
    dateSignal = pyqtSignal(str)  # 放个信号来实现跨窗口信息传递

    def __init__(self, parent=None):
        QWidget.__init__(self)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Calendar')
        self.cal = QCalendarWidget(self)

        self.cal.setGridVisible(True)
        self.cal.selectionChanged.connect(self.showDate)
        self.label = QLabel(self)
        self.getdate = self.cal.selectedDate()
        self.strDate =str(self.getdate.toPyDate())
        self.label.setText(self.strDate)
        self.date=self.strDate

        #确认按钮布局
        self.btn_layout=QHBoxLayout()
        self.btn=QPushButton('确认')
        self.btn.setFixedWidth(130)
        self.btn.clicked.connect(self.click_btn)
        self.btn_layout.addWidget(self.btn)
        self.btn_layout.setAlignment(Qt.AlignRight)

        vbox = QVBoxLayout()
        vbox.addWidget(self.cal)
        vbox.addWidget(self.label)
        vbox.addLayout(self.btn_layout)

        self.setLayout(vbox)

    def showDate(self):
        date = self.cal.selectedDate()
        self.label.setText(str(date.toPyDate()))

    def click_btn(self):
        content =str(self.cal.selectedDate().toPyDate())
        self.dateSignal.emit(content)  # 发射信号
        self.close()


class DataTable(QTableWidget):
    doubel_Signal=pyqtSignal(dict)
    def __init__(self):
        super(DataTable, self).__init__()
        # self.date_list=date_list  #['2020-10-20','2020-10-21',..]  #查询的日期
        # self.data=data  #{'A':['x|y','x|y'],'B':['x|y','x|y'],...}   x为当日安排工时，y为当日制作工时
        self.data={}  #{'xx': [['2020-11-02', '5.4(0)'], ['2020-11-03', '5.4(0)'], ...]}
        self.setShowGrid(True)
        self.verticalHeader().setDefaultSectionSize(30)
        self.verticalHeader().sectionDoubleClicked.connect(self._vclick)
        self.horizontalHeader().setDefaultSectionSize(100)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)



    def setData(self,date_list,data):
        if data:
            self.clear()
            self.data=data
            cc=len(date_list)
            rc=len(data.keys())
            print(rc,cc)
            self.setColumnCount(cc)
            self.setRowCount(rc)   #人员数
            self.head_list=date_list
            weekend_index=self.get_weekday_index(date_list)
            print('weekend_index:',weekend_index)
            artist_list=list(data.keys())
            self.setHorizontalHeaderLabels(self.head_list)
            self.setVerticalHeaderLabels(artist_list)
            for r in range(self.rowCount()):
                k = artist_list[r]
                v = data[k]
                for c in range(self.columnCount()):
                    text=v[c][1]
                    item=QTableWidgetItem()
                    item.setText(text)
                    item.setTextAlignment(Qt.AlignCenter)
                    if c in weekend_index:
                        item.setBackground(QBrush(QColor('#9C9C9C')))
                    self.setItem(r,c,item)
        print('setData over')
    def _vclick(self,index):
        all_assigned_workhour=0
        all_submit_workhour=0
        if self.data:
            artist=self.verticalHeaderItem(index).text() if self.verticalHeaderItem(index) else ''
            if self.data[artist]:
                data_list=self.data[artist]
                for data in data_list:
                    workshow=data[1]
                    assigned_workhour,last=workshow.split('(')
                    submit_workhour=last.split(')')[0]
                    all_assigned_workhour+=float(assigned_workhour)
                    all_submit_workhour+=float(submit_workhour)
        print('{} 安排时长{}  提交时长{}'.format(artist,all_assigned_workhour,all_submit_workhour))
        # return all_assigned_workhour,all_submit_workhour
        self.doubel_Signal.emit({'artist':artist,'all_workhour':'{}({})'.format(all_assigned_workhour,all_submit_workhour)})

    def getWeekday(self,date):
        """
        判定周末
        :return:
        """
        date_list=[int(s) for s in date.split('-')]
        weekday=datetime.datetime(*date_list).strftime("%w")
        return weekday

    def get_weekday_index(self,date_list):
        """
        获取对应为周末的日期
        :param date_list:
        :return:
        """
        index_list=[]
        if date_list:
            try:
                for date in date_list:
                    if self.getWeekday(date) == '0':
                        index_list.append(date_list.index(date))
            except Exception as get_weekday_index_ERR:
                print(str(get_weekday_index_ERR))
        return index_list

class Statistical(QWidget):

    def __init__(self,parent):
        super(Statistical, self).__init__()
        self.parent=parent
        self.now=datetime.datetime.now()
        self.start_date=''
        self.end_date=''
        self.setStyleSheet('background:{}'.format(parent.ramp))
        self.setWindowIcon(parent.nicon)
        self.date_btn_style = '''QPushButton{color:black}
                                  QPushButton:hover{color:#FF8C00}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:10px}
                                  QPushButton{padding:5px 10px}'''
        #          QPushButton{background-color:#FFDEAD}
        self.per_btn_style = '''QPushButton{color:black}
                                  QPushButton:hover{color:#FF8C00}

                                  QPushButton{border:2px}
                                  QPushButton{border-radius:10px}
                                  QPushButton{padding:5px 10px}'''
        self.bold_font=QFont('',10,65)

        self.setWindowTitle('部门统计')
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.setMinimumWidth(800)
        self.main_layout=QVBoxLayout()
        self.choose_layout=QHBoxLayout()
        self.start_btn=QPushButton('--')
        self.start_btn.setStyleSheet(self.date_btn_style)
        self.start_btn.clicked.connect(self._open_start_calendar)
        self.end_btn=QPushButton('--')
        self.end_btn.setStyleSheet(self.date_btn_style)
        self.end_btn.clicked.connect(self._open_end_calendar)
        self.choose_layout.addWidget(self.start_btn)
        self.choose_layout.addWidget(self.end_btn)
        self.quick_layout=QHBoxLayout()
        self.last_week=QPushButton('上周')
        self.last_week.setStyleSheet(self.per_btn_style)
        self.last_week.clicked.connect(self._set_last_week)
        self.current_week=QPushButton('本周')
        self.current_week.setStyleSheet(self.per_btn_style)
        self.current_week.clicked.connect(self._set_current_week)
        self.last_month = QPushButton('上月')
        self.last_month.setStyleSheet(self.per_btn_style)
        self.last_month.clicked.connect(self._set_last_month)
        self.current_month=QPushButton('本月')
        self.current_month.setStyleSheet(self.per_btn_style)
        self.current_month.clicked.connect(self._set_current_month)

        self.quick_layout.addWidget(self.last_week)
        self.quick_layout.addWidget(self.current_week)
        self.quick_layout.addWidget(self.last_month)
        self.quick_layout.addWidget(self.current_month)
        self.work_table=DataTable()
        self.work_table.doubel_Signal.connect(self.update_aritst_statist)
        self.statist_layout=QVBoxLayout()
        self.statist_layout.setAlignment(Qt.AlignCenter)
        self.artist_statist_layout=QHBoxLayout()
        self.artist_statist_layout.setSpacing(20)
        self.artist_label=QLabel('艺术家:')
        self.artist_label.setStyleSheet('background:{}'.format('#CFCFCF'))
        self.artist_label.setFont(self.bold_font)
        self.artist_show_label=QLabel('')
        self.artist_show_label.setStyleSheet('background:{}'.format('#CFCFCF'))
        self.artist_statist_label=QLabel('个人总时长:')
        self.artist_statist_label.setFont(self.bold_font)
        self.artist_statist_label.setStyleSheet('background:{}'.format('#CFCFCF'))
        self.artist_statist_workhour_label=QLabel('0')
        self.artist_statist_workhour_label.setStyleSheet('background:{}'.format('#CFCFCF'))
        self.artist_statist_layout.addWidget(self.artist_label)
        self.artist_statist_layout.addWidget(self.artist_show_label)
        self.artist_statist_layout.addWidget(self.artist_statist_label)
        self.artist_statist_layout.addWidget(self.artist_statist_workhour_label)
        self.department_statist_layout=QHBoxLayout()

        self.department_statist_label=QLabel('部门总时长:')
        self.department_statist_label.setFont(self.bold_font)
        self.department_statist_label.setStyleSheet('background:{}'.format('#CFCFCF'))
        self.department_statist_workhour_label=QLabel('0')
        self.department_statist_workhour_label.setStyleSheet('background:{}'.format('#CFCFCF'))
        self.department_statist_layout.addWidget(self.department_statist_label)
        self.department_statist_layout.addWidget(self.department_statist_workhour_label)
        self.statist_layout.addLayout(self.artist_statist_layout)
        self.statist_layout.addLayout(self.department_statist_layout)
        self.main_layout.addLayout(self.choose_layout)
        self.main_layout.addLayout(self.quick_layout)
        self.main_layout.addWidget(self.work_table)
        self.main_layout.addLayout(self.statist_layout)

        self.setLayout(self.main_layout)

        self.init_data()

    def init_data(self):
        self._set_current_week()
        print('init_data 001')
        # department_ori_data,department_data=self.get_department_data()
        department_ori_data, department_data = self.get_department_data(self.parent.department, self.start_date,
                                                                        self.end_date)
        # print('department_ori_data:',department_ori_data)
        # print('department_data:',department_data)
        self.update_table(department_data)

    def update_data(self):
        print('update_data 001')
        # department_ori_data,department_data=self.get_department_data()
        department_ori_data,department_data=self.get_department_data(self.parent.department,self.start_date,self.end_date)
        # print('department_ori_data:',department_ori_data)
        # print('department_data:',department_data)
        self.update_table(department_data)

    def get_department_artists(self,department):
        """
        根据传入department，返回该部门的所以人员列表
        :return:
        """
        department_artists=[]
        time_connect, time_cursor = self.parent._init_scheduler_db()
        select_sql="select artist from timeaxis.r_account where conf_department_id=" \
                   "(select cg_id from timeaxis.r_department where name='{}')".format(department)
        try:
            time_cursor.execute(select_sql)
            result=time_cursor.fetchall()
            if result:
                for i in result:
                    department_artists.append(i[0])
        except Exception as get_department_artists_ERR:
            print('get_department_artists_ERR:',str(get_department_artists_ERR))
        finally:
            time_connect.close()
        return department_artists

    # def list_to_dict(self,task_list):
    #     """
    #     将任务列表转成字典形式
    #     :param task_list:
    #     :return:
    #     """
    #     data={}
    #     if task_list:
    #         for i in range(len(task_list)):
    #             data[str(i)]=task_list[i]
    #     # print('list_to_dict OK')
    #     return data
    def list_to_dict(self,task_list,date):
        """
        将任务列表转成字典形式
        :param task_list: [{'id': '', 'task_type': 'cgtw', 'start_date':xx,...},{...},..]
        :param   date :给定日期
        :return: 返回当日的所有任务 ['0':{...},'1':{...},'2':{...},...]
        """
        data={}
        if task_list:
            # print('list_to_dict:',task_list)
            the_date_task_lists=[]
            for task_data in task_list:
                if task_data['date']==date:
                    the_date_task_lists.append(task_data)
            if the_date_task_lists:
                for i in range(len(the_date_task_lists)):
                    data[str(i)]=task_list[i]

        return data


    def get_department_scheduler_assinged_data(self,department_artists,start_date,end_date):
        """
        直接获取该部门所有人员的当前排期系统里读取到的任务，同时格式为department_ori_data: {'蔡宝润': [['2020-10-19', None, None], ['2020-10-20', None, None], ['2020-10-21', None, None]]}
department_data: {'蔡宝润': [['2020-10-19', '10.0(0)'], ['2020-10-20', '12.0(0)'], ['2020-10-21', '12.0(0)']]}
        :param department_artists:
        :param start_date:
        :param end_date:
        :return: 返回的只是排期系统上的安排工时，没有替换本地数据
        """
        data_list=self.parent.getEveryDay(start_date,end_date)
        department_ori_data = {}
        department_assigned_data={}
        if department_artists:
            for artist in department_artists:
                assigned_tasks=self.parent.get_alltask_by_range_date(artist,start_date,end_date)  #获取该人员指定日期里的所有任务列表,已切拆分为每天任务
                for date in data_list:
                    assigned_workhour = self.extra_assigned_workhour(date,assigned_tasks)
                    # show_hour = '{}(0)'.format(round(assigned_workhour, 2))    #显示工时格式化为 安排工时(提交工时),
                    show_hour = '{}_0'.format(round(assigned_workhour, 2))   #显示工时格式化为 安排工时(提交工时),
                    per_info = [date, show_hour]
                    if artist not in department_assigned_data.keys():
                        department_assigned_data[artist] = [per_info]
                    else:
                        department_assigned_data[artist].append(per_info)
                    if artist not in department_ori_data.keys():
                        # department_ori_data[artist] = [[date, self.list_to_dict(assigned_tasks), {}]]
                        department_ori_data[artist] = [[date, self.list_to_dict(assigned_tasks,date), {}]]
                    else:
                        department_ori_data[artist].append([date, self.list_to_dict(assigned_tasks,date), {}])
                        # department_ori_data[artist].append([date, self.list_to_dict(assigned_tasks), {}])

        return department_ori_data,department_assigned_data

    # def get_department_data(self):
    #     """
    #     从note表中获取本地存储的所有该部门的数据
    #     :return:
    #     """
    #     department_artists=self.get_department_artists(self.parent.department)
    #     # department_ori_data=  {}   #从note表里查询的原始数据
    #     try:
    #         department_ori_data,department_data=self.get_department_scheduler_assinged_data(department_artists,self.start_date,self.end_date)
    #     except Exception as get_department_scheduler_assinged_data_ERR:
    #         print('get_department_scheduler_assinged_data_ERR:',str(get_department_scheduler_assinged_data_ERR))
    #     #department_data={}   #从note查询到的数据过滤后的工时数据
    #     time_connect, time_cursor = self.parent._init_taskprogress_db()
    #     select_sql="select artist,date,assigned_tasks,submit_tasks from note where department='{}' and date>='{}' and date<='{}'" \
    #                "  ".format(self.parent.department,self.start_date,self.end_date)#self.start_date '2020-10-01'
    #     search_data={}
    #
    #     try:
    #         time_cursor.execute(select_sql)
    #         result=time_cursor.fetchall()
    #         if result:   #这是查询本地有手动填写的人员信息
    #             for i in result:
    #                 artist=i[0]
    #                 date=i[1]
    #                 assigned_tasks=i[2]
    #                 submit_tasks=i[3]
    #                 if artist not in search_data.keys():
    #                     search_data[artist]= department_ori_data[artist]#  self.parent.get_alltask_by_date(artist, date)  #只循环一次，获取当前人员的该日排期数据前后15天所有数据
    #                 # print('type(assigned_tasks):',type(assigned_tasks))
    #                 assigned_workhour=self.extra_assigned_workhour(date,assigned_tasks) if assigned_tasks else self.get_the_date_workhour(search_data[artist],date)#这里查询的仅为note已填写的当前已分配数据
    #                 #当但如果当日没有提交的话，应该以替换的方式去现实安排工时，即一开始将该部门所有人员的排期软件里查询到的安排任务
    #                 #进行统计，然后查询本地记录的安排任务，如果本地存在那么就替换掉即时查询的排期上的安排任务。
    #                 print('get_department_data:',artist, date, assigned_workhour)
    #                 submit_workhour=self.extra_submit_workhour(submit_tasks)
    #                 show_hour='{}({})'.format(round(assigned_workhour,2),round(submit_workhour,2))
    #                 per_info=[date,show_hour]
    #                 #直接更新
    #                 scheduler_assined_data=department_data[artist]
    #                 for g in range(len(scheduler_assined_data)):
    #                     if date==scheduler_assined_data[g][0]:  #当原查询日常里有该日期时,替换掉
    #                         scheduler_assined_data[g]=per_info  #字典可以直接替换值，不动keys
    #
    #     except Exception as get_department_data_ERR:
    #         print('get_department_data_ERR:',str(get_department_data_ERR))
    #     finally:
    #         time_connect.close()
    #
    #     return department_ori_data,department_data
    def get_department_data(self, department, start_date, end_date):
        """
        还是要从daily里去取，因为note存储的只是当天的任务填写，daily是可以后面补填的
        :param department:
        :param start_date:
        :param end_date:
        :return:
        """
        print('get_department_data 001')
        department_artists = self.get_department_artists(department)
        # department_ori_data=  {}   #从note表里查询的原始数据
        try:
            department_ori_data, department_data = self.get_department_scheduler_assinged_data(department_artists,
                                                                                               start_date, end_date)
            print('get_department_data 002')
            # for k,v in department_ori_data.items():
            #     print(k,len(v),v)
        except Exception as get_department_scheduler_assinged_data_ERR:
            print('get_department_scheduler_assinged_data_ERR:', str(get_department_scheduler_assinged_data_ERR))
        # department_data={}   #从note查询到的数据过滤后的工时数据
        time_connect, time_cursor = self.parent._init_taskprogress_db()
        # select_sql="select artist,date,assigned_tasks,submit_tasks from note where department='{}' and date>='{}' and date<='{}'" \
        #            "  ".format(department,start_date,end_date)#self.start_date '2020-10-01'
        select_sql = "select artist,date,show_workhour,worktime from daily where department='{}' and date>='{}' and date<='{}'".format(
            department, start_date, end_date)

        search_data = {}

        try:
            print('get_department_data 002.5')
            time_cursor.execute(select_sql)
            result = time_cursor.fetchall()
            print('get_department_data 003')
            if result:  # 这是查询本地有手动填写的人员信息
                print('get_department_data 004')
                artist_date_allhour = {}  # {'artist1' : {'2020-11-20':'10_8','2020-11-22':'12_4',...},
                # 'artist2' : {'2020-11-20':'4_4','2020-11-25':'11_6',...}}
                artist_date_task_list_map = {}  # {'artist1' : {'2020-11-20':[(show_workhour,worktime),(show_workhour,worktime),...],
                # '2020-11-22':[(show_workhour,worktime),(show_workhour,worktime),...],
                #                              'artist2' : {'2020-11-20':[(show_workhour,worktime),(show_workhour,worktime),...],
                for i in result:
                    artist = i[0]
                    date = i[1]
                    show_workhour = i[2]
                    worktime = i[3]

                    # assigned_workhour= show_workhour #float(show_workhour) if show_workhour else self.get_the_date_workhour(search_data[artist],date)

                    # submit_workhour = worktime   #self.extra_submit_workhour(submit_tasks)
                    if artist not in artist_date_task_list_map.keys():
                        artist_date_task_list_map[artist] = {date: [(show_workhour, worktime)]}
                    else:
                        value = artist_date_task_list_map[artist]
                        if date not in value.keys():
                            artist_date_task_list_map[artist][date] = [(show_workhour, worktime)]
                        else:
                            artist_date_task_list_map[artist][date].append((show_workhour, worktime))
                    # show_hour='{}_{}'.format(round(assigned_workhour,2),round(submit_workhour,2))
                    # per_info=[date,show_hour]
                # 计算artist_date_allhour
                print('get_department_data 005')
                if artist_date_task_list_map:
                    for a, v in artist_date_task_list_map.items():
                        the_artist = a

                        date_hour_map = {}  # {'2020-11-20':'10_8','2020-11-22':'12_4',...}
                        for d, sw_list in v.items():  # v = {'2020-11-20':[(show_workhour,worktime),(show_workhour,worktime),...]
                            the_date = d
                            all_s = 0
                            all_w = 0
                            for sw in sw_list:
                                s = sw[0]
                                w = sw[1]
                                all_s += float(s)
                                all_w += float(w)
                            show_hour = '{}_{}'.format(round(all_s, 2), round(all_w, 2))
                            # if the_date not in date_hour_map.keys():
                            date_hour_map[the_date] = show_hour

                        # if the_artist not in artist_date_allhour.keys():
                        artist_date_allhour[the_artist] = date_hour_map
                        # else:
                        #     artist_date_allhour[the_artist]
                if artist_date_allhour:  # {'张谷雷': {'2020-11-16': '12.0_8.0', '2020-11-20': '0.0_9.0', '2020-11-19': '2.0_5.0'}, '黄锐': {...},...}
                    print('artist_date_allhour:', artist_date_allhour)
                    for ar, sh in artist_date_allhour.items():
                        # 直接更新 ar:'张谷雷'
                        #   sh :{'2020-11-16': '12.0_8.0', '2020-11-20': '0.0_9.0', '2020-11-19': '2.0_5.0'},
                        scheduler_assined_data = department_data[
                            ar]  # [['2020-11-16', '8.33_0'], ['2020-11-17', '8.33_0'],
                        for g in range(len(scheduler_assined_data)):
                            p_date = scheduler_assined_data[g][0]
                            if p_date in sh:  # 当原查询日常里有该日期时,替换掉
                                scheduler_assined_data[g][1] = sh[p_date]  # 字典可以直接替换值，不动keys

        except Exception as get_department_data_ERR:
            print('get_department_data_ERR:', str(get_department_data_ERR))
        finally:
            time_connect.close()

        return department_ori_data, department_data

    def extra_assigned_workhour(self,date,tasks):
        """
        传入当日分配的任务字典，提取当日所有分配任务总时长
        这里需要注意的是，当该日为空时，需要去排期软件上查询那一天的安排
        :param artist: 该制作人员
        :param date:  该日期
        :param tasks:
        :return:
        """
        all_workhour=0
        if tasks:
            if isinstance(tasks,dict):
                for k,v in tasks.items():
                    show_workhour=v['show_workhour']
                    all_workhour+=float(show_workhour)
            elif isinstance(tasks,list):
                for i in tasks:
                    if i['date']==date:
                        # print('iii:',i)
                        show_workhour=i['show_workhour']
                        all_workhour+=float(show_workhour)
        return all_workhour

    def extra_submit_workhour(self,tasks):
        """
        传入当日提交的任务字典，提取当日所有提交任务总时长。

        :param tasks:
        :return:
        """
        all_workhour=0
        if tasks:
            for k,v in tasks.items():
                show_workhour=v['worktime']
                all_workhour+=float(show_workhour)
        return all_workhour

    def get_the_date_workhour(self,all_data_list,date):
        """
        获取指定天里的所有任务的总工时
        :param all_data_list:
        :return:
        """
        all_workhour=0
        if all_data_list:
            for data in all_data_list:
                if data['date']==date:
                    show_workhour = data['show_workhour']
                    all_workhour += float(show_workhour)
        return all_workhour

    def update_table(self,data):
        """
        更新表格内容
            date=['2020-10-01','2020-10-02','2020-10-03','2020-10-04','2020-10-05']
             data={'A':['4(5)','3(5)','4|5','3|5','4|5'],'B':['4|5','3|5','4|5','3|5','4|5'],'C':['4|5','3|5','4|5','3|5','4|5']}
        :param data:  {'张洲': [['2020-10-11', '0(0)'], ['2020-10-12', '0(0)'],....]],'李伟': [['2020-10-12', '0(0)'], ['2020-10-13', '0(0)'], ...]]}
        :return:
        """
        print('update_table  001')
        formate_data={}
        date_list=self.parent.getEveryDay(self.start_date,self.end_date)#self.start_date '2020-10-01'

        if data:
            for k,v in data.items():  #每人数据
                info_list=[]
                has_date_list = []  # 记录该人员已记录的所有日期
                for per in v:
                    has_date_list.append(per[0])
                for d in date_list:   #每日期填充
                    per_data=None
                    if d not in has_date_list:
                        # per_data=[d,'0(0)']
                        per_data=[d,'0_0']
                    else:
                        per_data=v[has_date_list.index(d)]
                    info_list.append(per_data)
                formate_data[k]=info_list
        # print('formate_data:',formate_data)
        print('update_table  003')
        self.work_table.setData(date_list,formate_data)
        print('update_table  004')
        self.update_department_statist(formate_data)
        print('update_table  over')

    def update_aritst_statist(self,data):
        """
        更新个人统计数据
        :return:
        """
        if data:
            self.artist_show_label.setText(data['artist'])
            self.artist_statist_workhour_label.setText(data['all_workhour'])

    def update_department_statist(self,data):
        print('update_department_statist start')
        print('update_department_statist data :',data)
        department_workhour='0(0)'
        if data:
            all_assigned_workhour=0
            all_submit_workhour=0
            print(data.keys())
            for v in data.values():
                for data in v:
                    workshow=data[1]
                    # assigned_workhour, last = workshow.split('(')
                    assigned_workhour, submit_workhour = workshow.split('_')
                    # submit_workhour = last.split(')')[0]
                    all_assigned_workhour += float(assigned_workhour)
                    all_submit_workhour += float(submit_workhour)
            # department_workhour='{}({})'.format(all_assigned_workhour,all_submit_workhour)
            department_workhour='{}_{}'.format(all_assigned_workhour,all_submit_workhour)
        self.department_statist_workhour_label.setText(department_workhour)

        print('update_department_statist over')

    def _open_start_calendar(self):
        self.calwindow=Calendar()
        self.calwindow.dateSignal.connect(self._set_start)
        self.calwindow.show()

    def _open_end_calendar(self):
        self.calwindow=Calendar()
        self.calwindow.dateSignal.connect(self._set_end)
        self.calwindow.show()

    def _set_start(self,date):
        self.start_btn.setText(date)
        self.start_date=date

    def _set_end(self,date):
        self.end_btn.setText(date)
        self.end_date=date
        self.update_data()

    def _set_last_week(self):
        self.start_date,self.end_date=self.get_last_week()
        self.start_btn.setText(self.start_date)
        self.end_btn.setText(self.end_date)
        self.update_data()

    def _set_current_week(self):
        self.start_date,self.end_date=self.get_current_week()
        self.start_btn.setText(self.start_date)
        self.end_btn.setText(self.end_date)
        self.update_data()

    def _set_last_month(self):
        self.start_date,self.end_date=self.get_last_month()
        self.start_btn.setText(self.start_date)
        self.end_btn.setText(self.end_date)
        self.update_data()

    def _set_current_month(self):
        self.start_date,self.end_date=self.get_current_month()
        self.start_btn.setText(self.start_date)
        self.end_btn.setText(self.end_date)
        self.update_data()

####计算函数
    def get_current_week(self):
        """
        返回当前时间的上一周的开始和结束时间
        """
        this_week_start = self.now - datetime.timedelta(days=self.now.weekday())
        this_week_end = self.now + datetime.timedelta(days=6 - self.now.weekday())

        return this_week_start.strftime("%Y-%m-%d"), this_week_end.strftime("%Y-%m-%d")

    def get_last_week(self):
        """
        获取上周起始与结束日期
        :return:
        """
        last_week_start = self.now - datetime.timedelta(days=self.now.weekday() + 7)
        last_week_end = self.now - datetime.timedelta(days=self.now.weekday() + 1)

        return last_week_start.strftime("%Y-%m-%d"), last_week_end.strftime("%Y-%m-%d")

    def get_current_month(self):
        """
        计算本月起始与结束日期
        :return:
        """
        this_month_start = datetime.datetime(self.now.year, self.now.month, 1)
        this_month_end = datetime.datetime(self.now.year, self.now.month + 1, 1) - datetime.timedelta(
            days=1) + datetime.timedelta(
            hours=23, minutes=59, seconds=59)

        return this_month_start.strftime("%Y-%m-%d"), this_month_end.strftime("%Y-%m-%d")

    def get_last_month(self):
        """
        计算上月起始与结束日期
        :return:
        """
        this_month_start = datetime.datetime(self.now.year, self.now.month, 1)
        last_month_end = this_month_start - datetime.timedelta(days=1) + datetime.timedelta(
            hours=23, minutes=59, seconds=59)
        last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)

        return last_month_start.strftime("%Y-%m-%d"), last_month_end.strftime("%Y-%m-%d")

    def getWeekday(date):
        """
        判定周末
        :return:
        """
        date_list=[int(s) for s in date.split('-')]
        weekday=datetime.datetime(*date_list).strftime("%w")
        return weekday


if __name__ == '__main__':
    app=QApplication(sys.argv)
    date=['2020-10-01','2020-10-02','2020-10-03','2020-10-04','2020-10-05']
    data={'A':['4(5)','3(5)','4|5','3|5','4|5'],'B':['4|5','3|5','4|5','3|5','4|5'],'C':['4|5','3|5','4|5','3|5','4|5']}
    s=Statistical(date)
    s.show()
    sys.exit(app.exec_())